package com.ofek.eventos.util;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public abstract class LongTask<ReturnType> extends AsyncTask<Void,Integer,ReturnType>{

	private Exception exception;
	private ReturnType result;
	private ProgressDialog dialog;
	private Context context;
	private boolean withProgress;
	public LongTask(Context context) {
		this.context = context;
		withProgress = true;
	}
	public LongTask(Context context,boolean withProgress) {
		this.context = context;
		this.withProgress = withProgress;
	}
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		if (withProgress) dialog = ProgressDialog.show(context, "Loading", "Please wait...", true, true);
	}
	@Override
	protected ReturnType doInBackground(Void... params) {
		try {
			doTask();
			return result;
		} catch (Exception e) {
			setException(e);
			return null;
		}
	}
	
	protected void setException(Exception e) {
		exception = e;
	}
	protected void setResult(ReturnType result) {
		this.result = result;
	}
	@Override
	protected void onPostExecute(ReturnType result) {
		if (exception == null) onSuccess(result);
		else onError(exception);
		if (dialog!=null) dialog.dismiss();
	}
	/**
	 * use setResult to return result, use setException to return exception.
	 * @throws Exception
	 */
	protected abstract void doTask() throws Exception;
	/**
	 * runs on UI thread
	 * @param result
	 */
	protected abstract void onSuccess(ReturnType result);
	/**
	 * runs on UI thread
	 * @param e
	 */
	protected void onError(Exception e) {
		new AlertDialog.Builder(context).setMessage(e.toString()).setTitle("Error").show();
	}

}
